package com.zhao.dota.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhao.dota.mapper.MatchPlayerItemMapper;
import com.zhao.dota.model.Item;
import com.zhao.dota.model.MatchPlayerItem;
import com.zhao.dota.service.ItemService;
import com.zhao.dota.service.MatchPlayerItemService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MatchPlayerItemServiceImpl extends ServiceImpl<MatchPlayerItemMapper, MatchPlayerItem> implements MatchPlayerItemService {

    @Resource
    private ItemService itemService;

    @Override
    public int saveList(List<MatchPlayerItem> list) {
        int count = 0;
        for (MatchPlayerItem playerItem : list) {
            if (count == 0) {
                count += deleteByMatchId(playerItem.getMatchId());
            }
            Item item = itemService.getByName(playerItem.getName());
            BeanUtils.copyProperties(item, playerItem);
            playerItem.setId(null);
            playerItem.setItemId(item.getId());
            count += save(playerItem) ? 1 : 0;
        }
        return count;
    }

    @Override
    public List<MatchPlayerItem> findByMatchId(Integer matchId) {
        LambdaQueryWrapper<MatchPlayerItem> query = Wrappers.lambdaQuery(MatchPlayerItem.class)
                .eq(MatchPlayerItem::getMatchId, matchId);
        return list(query);
    }

    private int deleteByMatchId(Integer matchId) {
        LambdaQueryWrapper<MatchPlayerItem> query = Wrappers.lambdaQuery(MatchPlayerItem.class).eq(MatchPlayerItem::getMatchId, matchId);
        return baseMapper.delete(query);
    }

}
